//
//  BDEvaluationViewController.m
//  BeidouMall
//
//  Created by qie on 16/4/14.
//  Copyright © 2016年 qie. All rights reserved.
//

#import "BDEvaluationViewController.h"
#import "RatingBar.h"
#import "BDEvaluationTableViewCell.h"

@interface BDEvaluationViewController () <RatingBarDelegate,UITextViewDelegate>

{
    NSMutableArray *_evaluationList;
    NSString *commodityId;
    NSString *commit_orderId;
    NSString *level;
    NSString *content;
    BOOL hasEvaLuate;
    UITextView *_nowEditTextView;
    NSInteger index;
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation BDEvaluationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = NSLocalizedString(@"Comments", nil);
    _evaluationList = [[NSMutableArray alloc] init];
    [self reloadData:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark Private method

- (void)reloadData:(id) sender {
    [_evaluationList removeAllObjects];
    index = 0;
    for (NSDictionary *commodityDic in self.commodities) {
        NSString *commId = commodityDic[@"commodity"][@"commodityId"];
        NSString *url = [NSString stringWithFormat:@"%@%@?orderId=%@&commodityId=%@",
                         [BDNetworking shareInstance].baseUrl,
                         Evaluation_Query,
                         self.orderId,
                         commId];
        [[BDNetworking shareInstance] postWithUrl:url sid:nil method:@"GET" parameters:nil completionHandler:^(NSObject *results, NSError *error) {
            if (error != nil) {
                NSLog(@"获取评论失败:%@",error);
                [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"get comments failed", nil)];
            } else {
                NSLog(@"result = %@",results);
                index++;
                if ([results isEqual:[NSNull null]] || results == nil) {// 未评论
                    NSDictionary *dic = @{@"commodityId":commId,
                                          @"evaluationContents":[NSArray array]};
                    [_evaluationList addObject:dic];
                } else {
                    [_evaluationList addObject:results];
                }
                
                if (index == self.commodities.count) {// 最后一次循环
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self.tableView reloadData];
                        CGFloat height = 400.0 * self.commodities.count;
                        self.tableView.contentSize =CGSizeMake(0,height);
                    });
                }
            }
        }];
    }
}

- (void)commitEvaluation {
    if (content.length == 0) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"comments is blank", nil)];
    } else {
        // EVALUATION:评论 APPEND:追加评论 EVALUATION_REPLY:商家回复 APPEND_REPLY:商家回复追加评论
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view withText:NSLocalizedString(@"Submitting", nil)];
        if (level == nil) {
            level = @"";
        }
        NSDictionary *parameters = @{@"commodityId":commodityId,
                                     @"orderId":commit_orderId,
                                     @"level":level,
                                     @"content":content,
                                     @"type":hasEvaLuate ? @"APPEND" : @"EVALUATION"};
        NSString *url = [NSString stringWithFormat:@"%@%@",[BDNetworking shareInstance].baseUrl,Evaluation_Query];
        
        [[BDNetworking shareInstance] postWithUrl:url sid:nil method:@"POST" parameters:parameters completionHandler:^(NSObject *results, NSError *error) {
            level = nil;
            if (error != nil) {
                NSLog(@"提交评论失败:%@",error);
                hud.labelText = NSLocalizedString(@"Submit Failed", nil);
                [hud hideAfterDelay:0.5];
            } else {
                hud.labelText = NSLocalizedString(@"Released", nil);
                [hud hideAfterDelay:0.5];
                NSLog(@"result = %@",results);
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2* NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self reloadData:nil];
                });
            }
        }];
    }
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.commodities.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BDEvaluationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"evaluationCell"];
    // 评分提示
    UILabel *promitLabel = [(UILabel *)cell viewWithTag:107];
    promitLabel.hidden = YES;
    // 商品图片
    NSString *storeImageUrl = self.commodities[indexPath.row][@"commodity"][@"icon"];
    UIImageView *storeImageView = (UIImageView *)[cell viewWithTag:101];
    if (![storeImageUrl isEqual:[NSNull null]]) {
        NSInteger width = storeImageView.width * 2;
        NSInteger height = storeImageView.height * 2;
        storeImageUrl = [NSString stringWithFormat:@"%@?dp_cmd=/imageView2/mode/2/w/%ld/h/%ld/",storeImageUrl,(long)width,(long)height];
        [storeImageView sd_setImageWithURL:[NSURL URLWithString:storeImageUrl] placeholderImage:[UIImage imageNamed:@"image_empty"]];
    }
    // 评分星星
    UIView *containerView = [cell viewWithTag:102];
    RatingBar *ratingBar = [[RatingBar alloc] init];
    ratingBar.frame = CGRectMake(0, 0, 269, 60);
    [ratingBar setImageDeselected:@"ratingbar_unselected" halfSelected:nil fullSelected:@"ratingbar_selected" andDelegate:self];
    [containerView addSubview:ratingBar];
    for (NSDictionary *goodDic in _evaluationList) {// 每一个商品
        NSString *goodID = goodDic[@"commodityId"];
        NSString *commID = self.commodities[indexPath.row][@"commodity"][@"commodityId"];
        if ([goodID isEqualToString:commID]) {
            if ([goodDic valueForKey:@"level"]) {
                ratingBar.isIndicator = YES;//指示器，就不能滑动了，只显示评分结果
                CGFloat Goodlevel = [goodDic[@"level"] floatValue];
                [ratingBar displayRating:Goodlevel];
                promitLabel.hidden = YES;
            }
            break;
        }
    }
    
    // 之前的评论
    UIView *textContainerView = [cell viewWithTag:106];
    BOOL hasEVALUATION = NO;
    BOOL hasAPPEND = NO;
    
    for (UIView *view in textContainerView.subviews) {
        [view removeFromSuperview];
    }
    if (textContainerView.subviews.count == 0) {
        CGFloat totalAddHieght = 0;
        for (NSDictionary *goodDic in _evaluationList) {// 遍历每一条评论
            NSString *goodID = goodDic[@"commodityId"];
            NSString *commID = self.commodities[indexPath.row][@"commodity"][@"commodityId"];
            if ([goodID isEqualToString:commID]) {
                NSArray *evaluationArr = (NSArray *)goodDic[@"evaluationContents"];
                if (evaluationArr.count > 0) {
                    for (NSDictionary *dic in evaluationArr) {// 遍历每种评论
                        NSString *evaluationContent = dic[@"content"];
                        NSString *evaluationType = dic[@"type"];
                        UIColor *textColor;
                        if ([evaluationType isEqualToString:@"EVALUATION"]) {// 评论
                            textColor = RGBColor(170, 170, 170);
                            hasEVALUATION = YES;
                        }
                        if ([evaluationType isEqualToString:@"APPEND"]) {// 追加评论
                            evaluationContent = [NSString stringWithFormat:@"%@:%@",NSLocalizedString(@"Add comment", nil),evaluationContent];
                            textColor = RGBColor(170, 170, 170);
                            hasAPPEND = YES;
                        }
                        if ([evaluationType isEqualToString:@"EVALUATION_REPLY"]) {// 商家回复
                            evaluationContent = [NSString stringWithFormat:@"%@:%@",NSLocalizedString(@"Seller reply", nil),evaluationContent];
                            textColor = RGBColor(75, 205, 75);
                        }
                        if ([evaluationType isEqualToString:@"APPEND_REPLY"]) {// 商家回复追加评论
                            evaluationContent = [NSString stringWithFormat:@"%@:%@",NSLocalizedString(@"Seller reply Add comment", nil),evaluationContent];
                            textColor = RGBColor(75, 205, 75);
                        }
                        
                        CGFloat height = [evaluationContent boundingHeightWithSize:CGSizeMake(kScreen_Width - 16.0, CGFLOAT_MAX) font:[UIFont systemFontOfSize:14.0] lineSpace:8.0] + 8.0;
                        UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0.0, totalAddHieght, textContainerView.width, height)];
                        textView.text = evaluationContent;
                        textView.editable = NO;
                        textView.scrollEnabled = NO;
                        textView.backgroundColor = [UIColor clearColor];
                        textView.font = [UIFont systemFontOfSize:14.0];
                        textView.textColor = textColor;
                        totalAddHieght += height;
                        [textContainerView addSubview:textView];
                    }
                }
                break;
            }
        }
    }
    UIButton *commitButton = (UIButton *)[cell viewWithTag:105];
    UITextView *textView = (UITextView *)[cell viewWithTag:103];
    UILabel *placeholderLabel = (UILabel *)[cell viewWithTag:104];
    if (hasAPPEND) {// 追加评论
        [commitButton setHidden:YES];
        [placeholderLabel setHidden:YES];
        [textView setHidden:YES];
        cell.containerViewBottomHeight.constant = 0;
        //        cell.textViewBottomSpace.constant = 0;
    }
    if (hasEVALUATION && !hasAPPEND) {// 评论且还未追加评论
        textView.text = @"";
        [placeholderLabel setHidden:NO];
        [commitButton setTitle:NSLocalizedString(@"Add comment", nil) forState:UIControlStateNormal];
    }
    
    return cell;
}

#pragma mark - Tableview delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat totalAddHieght = 0;
    BOOL hasEVALUATION = NO;
    BOOL hasAPPEND = NO;
    for (NSDictionary *goodDic in _evaluationList) {// 每一个商品
        NSString *goodID = goodDic[@"commodityId"];
        NSString *commID = self.commodities[indexPath.row][@"commodity"][@"commodityId"];
        if ([goodID isEqualToString:commID]) {
            NSArray *evaluationArr = (NSArray *)goodDic[@"evaluationContents"];
            if (evaluationArr.count > 0) {
                for (NSDictionary *dic in evaluationArr) {// 每一条评价
                    NSString *evaluationContent = dic[@"content"];
                    NSString *evaluationType = dic[@"type"];
                    if ([evaluationType isEqualToString:@"EVALUATION"]) {// 评论
                        hasEVALUATION = YES;
                    }
                    if ([evaluationType isEqualToString:@"APPEND"]) {// 追加评论
                        evaluationContent = [NSString stringWithFormat:@"%@:%@",NSLocalizedString(@"Add comment", nil),evaluationContent];
                        hasAPPEND = YES;
                    }
                    if ([evaluationType isEqualToString:@"EVALUATION_REPLY"]) {// 商家回复
                        evaluationContent = [NSString stringWithFormat:@"%@:%@",NSLocalizedString(@"Seller reply", nil),evaluationContent];
                    }
                    if ([evaluationType isEqualToString:@"APPEND_REPLY"]) {// 商家回复追加评论
                        evaluationContent = [NSString stringWithFormat:@"%@:%@",NSLocalizedString(@"Seller reply Add comment", nil),evaluationContent];
                    }
                    CGFloat height = [evaluationContent boundingHeightWithSize:CGSizeMake(kScreen_Width - 16.0, CGFLOAT_MAX) font:[UIFont systemFontOfSize:14.0] lineSpace:8.0] + 8.0;
                    totalAddHieght += height;
                }
            }
        }
    }
    CGFloat textViewHieght = 0.0;
    if (hasAPPEND) {
        textViewHieght = 174.0 + 40.0;
    }
    return 337.0 + totalAddHieght - textViewHieght;
}

#pragma mark - textView delegate

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    _nowEditTextView = textView;
    return YES;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    //判断加上输入的字符，是否超过界限
    NSString *str = [NSString stringWithFormat:@"%@%@", textView.text, text];
    if (str.length > 256)
    {
        textView.text = [textView.text substringToIndex:256];
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Please input 1-256 characters", nil)];
        return NO;
    }
    
    UIView *superView = textView.superview;
    while (![superView isKindOfClass:[UITableViewCell class]]) {
        superView = superView.superview;
    }
    UITableViewCell *cell = (UITableViewCell *)superView;
    UILabel *placeholderLabel = (UILabel *)[cell viewWithTag:104];
    
    if (![text isEqualToString:@""]) {
        placeholderLabel.hidden = YES;
    }
    
    if ([text isEqualToString:@""] && range.location == 0 && range.length == 1) {// 空格
        placeholderLabel.hidden = NO;
    }
    return YES;
}

#pragma mark - scrollView delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if ([_nowEditTextView isFirstResponder]) {
        [_nowEditTextView resignFirstResponder];
    }
}

#pragma mark - UIAlertView delegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) { // 未评分提交
        level = @"5";
        [self commitEvaluation];
    }
}

#pragma mark - RatingBarDelegate

- (void)ratingChanged:(float)newRating {// 当这个控件有值的时候即使不滑动它也自己调用此方法
    NSLog(@"%@",[NSString stringWithFormat:@"%.0f",newRating]);
    level = [NSString stringWithFormat:@"%.0f",newRating];
}

#pragma mark - IBActions

- (IBAction)commitButtonPressed:(UIButton *)sender {
    UIView *superView = sender.superview;
    while (![superView isKindOfClass:[UITableViewCell class]]) {
        superView = superView.superview;
    }
    UITableViewCell *cell = (UITableViewCell *)superView;
    
    UITextView *textView = (UITextView *)[cell viewWithTag:103];
    
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    commodityId = self.commodities[indexPath.row][@"commodity"][@"commodityId"];
    commit_orderId = self.commodities[indexPath.row][@"orderId"];
    content = textView.text;
    
    hasEvaLuate = NO;
    for (NSDictionary *dic in _evaluationList) {
        NSString *commID = dic[@"commodityId"];
        if ([commID isEqualToString:commodityId]) {
            NSArray *evaluationArr = (NSArray *)dic[@"evaluationContents"];
            for (NSDictionary *evaDic in evaluationArr) {
                NSString *evaluationType = evaDic[@"type"];
                if ([evaluationType isEqualToString:@"EVALUATION"]) {// 已经有评论了
                    hasEvaLuate = YES;
                }
            }
        }
    }
    
    if ((level == nil || [level isEqualToString:@"0"]) && !hasEvaLuate) {
        NSString *msg = NSLocalizedString(@"You haven't comment, sure to submit?", nil);
        UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"" message:msg delegate:self cancelButtonTitle:NSLocalizedString(@"confirm", nil) otherButtonTitles:NSLocalizedString(@"cancel", nil), nil];
        [alter show];
    } else {
        [self commitEvaluation];
    }
}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
